var ajaxStarted = false;
var entries = Array();
var numberOfBoxes=0;
$(document).ready(function(){
  
  $(document).on("click",'#roomLevelTable tbody tr td:nth-last-of-type(1)',deleteRoomLevelClick);
  $('#btnNewRoom').click({mode:"room"},AddRoomLevelClick);
  $('#btnNewLevel').click({mode:"level"},AddRoomLevelClick);
  
  $("#roomLevelTable").on("click", " tr td", addInput);
  $(document).on("click", ".deleteInput" ,deleteInput); 
  $(document).on("click", "#submitChanges", subChanges);
});

function deleteRoomLevelClick() {
  
  
  if(!ajaxStarted)
  {
    if($(this).closest('tr').attr("class")==="level")
    {
      mode = "level";
      if(!confirm("Wollen Sie dieses Stockwerk und alle zugehörigen Räume wirklich löschen?"))
        return;
    }
    else
    {
      mode = "room";
      if(!confirm("Wollen Sie diesen Raum wirklich löschen?"))
        return;
    }
    ajaxStarted=true;
    $(this).empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    var td = this;
    var mode;
    
    $.post("ajax/updateLevelRoom.php",{action:"delete",target:mode,id:$(this).attr("objid")}).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
        if(mode === "room")
          $(td).closest('tr').fadeTo(400,0,function(){$(this).remove();});
        else if(mode === "level")
        {
          if(jsonData.partly === "full")
            $(td).closest('tr').attr("class","remove");
          else
          {
            $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/delete.png",
                       "width":"20px",
                       "alt":"X"}));
            alert(jsonData.message);
          }
          
          $('#roomLevelTable tbody tr td:nth-last-of-type(1)').each(function(){
            if($.inArray($(this).attr("objid"),jsonData.deletedRooms)>=0)
              $(this).closest('tr').attr("class","remove");
          });
          $('#roomLevelTable tbody tr.remove').fadeTo(400,0,function(){$(this).remove();})
        }
      }
      else
      {
        $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/delete.png",
                       "width":"20px",
                       "alt":"X"}));
        alert(jsonData.message);
      }
    }).fail(function(){
      $(td).empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
      ajaxStarted = false;
    });
  }
}

function AddRoomLevelClick(e) {
  if(!ajaxStarted)
  {
    ajaxStarted=true;
    var form;
    var table;
    if(e.data.mode === "level")
    {
      form="#newLevel";
      table="#newLevelTable";
    }
    else if(e.data.mode === "room")
    {      
      form="#newRoom";
      table="#newRoomTable";
    }
    $(table + ' tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    
    $.post("ajax/updateLevelRoom.php",$(form).serialize() + "&" + $.param({action:"add",mode:e.data.mode})).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
        $(table + ' tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty();
        
        if(e.data.mode === "level")
        {
          $('#roomLevelTable tbody').append(jsonData.row);
          $('#levelSelect').append(jsonData.option);
          $('.levelEdit').append(jsonData.option);
        }
        else if(e.data.mode === "room")
        {      
          var matchFound = false;
          $('#roomLevelTable tbody tr.level td:nth-last-of-type(1)').each(function(){
            if(matchFound)
            {
              var tr=$(this).closest('tr');
              tr.before(jsonData.row);
              if(tr.next('tr').attr('class')==="padding")
                tr.next('tr').remove();
              else
                tr.after($('<tr>').attr('class','padding').hide());
              
              matchFound = false;
            }
            
            if($(this).attr('objid').trim()===$.trim(jsonData.option))
              matchFound = true;
          });
          if(matchFound)
            {
              $('#roomLevelTable tbody').append(jsonData.row);
            }
        }
      }
      else
      {
        $(table + ' tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
        alert(jsonData.message);
      }
    }).fail(function(){
      $(table + ' tbody tr:nth-last-of-type(1) td:nth-last-of-type(1)').empty().append($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
      ajaxStarted = false;
    });
  }
}

function addInput()
{   
  if((typeof($(this).attr('name')) != 'undefined') && ($('input[name="'+$(this).attr('name')+'"]').length < 1) && ($('select[name="'+$(this).attr('name')+'"]').length < 1))
  {
        var text = $(this).text();
        var name = $(this).attr('name');
        entries[name] = text;
        $(this).text('');      // Inhalt des <td>-Tags löschen
        if($(this).attr('info') === 'level')
        {
          $(this).append($('<select>').attr({"name":name, "class":"levelEdit"}).append($('#levelSelect').html()))
                 .append($("<input>").attr({"type":"Button", "value":"Abbruch", "name":"abort", "class":"deleteInput"}));
        }
        else
        {
          $(this).append($("<input>").attr({"name":name, "type":"text", "value":text, "list":$(this).attr('info')}))
                 .append($("<input>").attr({"type":"Button", "value":"Abbruch", "name":"abort", "class":"deleteInput"}));
        }
        if(numberOfBoxes===0)
        {
            $('#submitArea').append($('<input>').attr({"type":"button", "value":"Übernehmen", "name":"submit", "id":"submitChanges"}));
        }
        numberOfBoxes++;     
   }            
}

function deleteInput()
{   
  $(this).prev().replaceWith(entries[$(this).prev().attr('name')]);
  $(this).remove();
  numberOfBoxes--;
  if(numberOfBoxes === 0)
   {
     $('#submitArea').empty();
   }
} 

function subChanges()
{
  if(!ajaxStarted)
  {
    $('#submitArea').empty().append($('<img>')
                .attr({"src":"../design/pictures/loading.gif",
                       "width":"20px",
                       "alt":"loading"}));
    ajaxStarted=true;
    $.post("ajax/updateLevelRoom.php",$('#roomLevelForm').serialize() + "&" + $.param({action:"update"})).done(function(data){
      var jsonData=$.parseJSON(data);
      if(jsonData.success === "true")
      {
        $('#submitArea').empty();
        numberOfBoxes = 0;
        $.each(jsonData.row,function(i,row){
          if(row["type"]==="room")
          {
          if(row["levelChanged"])
          {
            var matchFound = false;
            $('#roomLevelTable tbody tr.level td:nth-last-of-type(1)').each(function(){
              if(matchFound)
              {
                $('#roomLevelTable tbody tr.room td:nth-last-of-type(1)').each(function(){
                  if($(this).attr('objid').trim()===$.trim(row["room"]))
                    $(this).closest('tr').remove();
                });
                
                $(this).closest('tr').before(row["row"]);
                
                matchFound = false;
              }

              if($(this).attr('objid').trim()===$.trim(row["level"]))
                matchFound = true;
            });
            if(matchFound)
              {
                $('#roomLevelTable tbody tr.room td:nth-last-of-type(1)').each(function(){
                  if($(this).attr('objid').trim()===$.trim(row["room"]))
                    $(this).closest('tr').remove();
                });
                
                $('#roomLevelTable tbody').append(row["row"]);
              }
            }
            else
            {
              $('#roomLevelTable tbody tr.room td:nth-last-of-type(1)').each(function(){
                  if($(this).attr('objid').trim()===$.trim(row["room"]))
                    $(this).closest('tr').replaceWith(row["row"]);
                });
            }
          }
          else
          {
            $('#roomLevelTable tbody tr.level td:nth-last-of-type(1)').each(function(){
                  if($(this).attr('objid').trim()===$.trim(row["level"]))
                    $(this).closest('tr').replaceWith(row["row"]);
                });
            $('#levelSelect option').each(function(){
              if($(this).val()===row["level"])
                $(this).replaceWith(jsonData.option);
            });
          }
          });
        
          var i=0;
          var numberOfPaddings=0;
          $('#roomLevelTable tbody tr.padding').remove();
          $('#roomLevelTable tbody tr').each(function(){
            i++;
            if($(this).attr('class')!== 'undefined' && $(this).attr('class')==='level')
            {
              if((i-numberOfPaddings)%2)
              {
                numberOfPaddings++;
                $(this).closest('tr').after($('<tr>').attr({class:'padding',style:'display: none;'}))
              }
            }
          });
      }
      else
      {
        $('#submitArea').replaceWith($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
        alert(jsonData.message);
      }
    }).fail(function(){
      $('#submitArea').replaceWith()($('<img>')
                .attr({"src":"../design/pictures/error.png",
                       "width":"20px",
                       "alt":"X"}));
    }).always(function(){
      ajaxStarted = false;
    });
  }
}